<template>
	<view class="login">
		<uv-form labelPosition="left" labelWidth="auto" :model="loginForm">
			<uv-form-item label="用户" prop="username" borderBottom>
				<uv-input v-model="delivery.username" border="none" placeholder="请输入或扫描订单号" />
			</uv-form-item>
			<uv-form-item label="密码" prop="password" borderBottom>
				<uv-input v-model="delivery.password" border="none" placeholder="请输入或扫描订单号" />
			</uv-form-item>
			<uv-form-item label="验证码" prop="code" borderBottom>
				<uv-input v-model="delivery.code" border="none" placeholder="请输入或扫描订单号" />
				<div class="login-code">
					<img :src="codeUrl" @click="getCode" class="login-code-img"/>
				</div>
			</uv-form-item>
			<uv-form-item borderBottom>
				<uv-button type="primary" shape="circle" @click="submit" size="mini" class="ml-1">登录</uv-button>
			</uv-form-item>
		</uv-form>
	</view>
</template>

<script setup>
	import Cookies from "js-cookie";
	
	const codeUrl = ref('')
	const loginForm = ref({
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      })
	  
	const getCode = () => {
		getCodeImg().then(res => {
			this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
			if (this.captchaEnabled) {
				this.codeUrl = "data:image/gif;base64," + res.img;
				this.loginForm.uuid = res.uuid;
			}
		})
	}
	
	const getCookie = () => {
		const username = Cookies.get("username");
		const password = Cookies.get("password");
		const rememberMe = Cookies.get('rememberMe')
		loginForm.value = {
			username: username === undefined ? loginForm.value.username : username,
			password: password === undefined ? loginForm.value.password : decrypt(password),
			rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
		};
	}
	
	const login = () => {
		if (loginForm.value.rememberMe) {
			Cookies.set("username", loginForm.value.username, { expires: 30 });
			Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
			Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 });
		} else {
			Cookies.remove("username");
			Cookies.remove("password");
			Cookies.remove('rememberMe');
		}
		this.$store.dispatch("Login", loginForm.value).then(() => {
			
		}).catch(() => {
			this.loading = false;
			if (this.captchaEnabled) {
				this.getCode();
			}
		});
	}
</script>

<style>

</style>
